<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="刘清政">
  <meta name="keyword" content="hexo-theme">
  
    <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
      31-自定义错误 | Justin-刘清政的博客
    
  </title>
  <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  
<link rel="stylesheet" href="/css/style.css">

  
    
<link rel="stylesheet" href="/css/plugins/gitment.css">

  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.js"></script>
  
    
<script src="/js/qrious.js"></script>

  
  
    
<script src="/js/gitment.js"></script>

  
  

  
<meta name="generator" content="Hexo 4.2.0"></head>
<div class="wechat-share">
  <img src="/css/images/logo.png" />
</div>

  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>Justin-刘清政的博客</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">主页</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">标签</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">归档</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">关于我</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">主页</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">标签</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">归档</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">关于我</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>31-自定义错误</h2>



  <p class="post-date">2019-03-10</p>
    <!-- 不蒜子统计 -->
    <span id="busuanzi_container_page_pv" style='display:none' class="">
        <i class="icon-smile icon"></i> 阅读数：<span id="busuanzi_value_page_pv"></span>次
    </span>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><h2 id="使用-New-函数创建自定义错误"><a href="#使用-New-函数创建自定义错误" class="headerlink" title="使用 New 函数创建自定义错误"></a>使用 New 函数创建自定义错误</h2><p>创建自定义错误最简单的方法是使用 [<code>errors</code>]包中的 [<code>New</code>]函数。</p>
<p>在使用 New [函数]创建自定义错误之前，我们先来看看 <code>New</code> 是如何实现的。如下所示，是 [<code>errors</code> 包]中的 <code>New</code> 函数的实现。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Package errors implements functions to manipulate errors.</span></span><br><span class="line"><span class="keyword">package</span> errors</span><br><span class="line"></span><br><span class="line"><span class="comment">// New returns an error that formats as the given text.</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">New</span><span class="params">(text <span class="keyword">string</span>)</span> <span class="title">error</span></span> &#123;</span><br><span class="line">    <span class="keyword">return</span> &amp;errorString&#123;text&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// errorString is a trivial implementation of error.</span></span><br><span class="line"><span class="keyword">type</span> errorString <span class="keyword">struct</span> &#123;</span><br><span class="line">    s <span class="keyword">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(e *errorString)</span> <span class="title">Error</span><span class="params">()</span> <span class="title">string</span></span> &#123;</span><br><span class="line">    <span class="keyword">return</span> e.s</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>New</code> 函数的实现很简单。<code>errorString</code> 是一个[结构体]类型，只有一个字符串字段 <code>s</code>。第 14 行使用了 <code>errorString</code> 指针接受者（Pointer Receiver），来实现 <code>error</code> 接口的 <code>Error() string</code> [方法]。</p>
<p>第 5 行的 <code>New</code> 函数有一个字符串参数，通过这个参数创建了 <code>errorString</code> 类型的变量，并返回了它的地址。于是它就创建并返回了一个新的错误。</p>
<p>现在我们已经知道了 <code>New</code> 函数是如何工作的，我们开始在程序里使用 <code>New</code> 来创建自定义错误吧。</p>
<p>我们将创建一个计算圆半径的简单程序，如果半径为负，它会返回一个错误。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (  </span><br><span class="line">    <span class="string">"errors"</span></span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">    <span class="string">"math"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">circleArea</span><span class="params">(radius <span class="keyword">float64</span>)</span> <span class="params">(<span class="keyword">float64</span>, error)</span></span> &#123;  </span><br><span class="line">    <span class="keyword">if</span> radius &lt; <span class="number">0</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>, errors.New(<span class="string">"Area calculation failed, radius is less than zero"</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> math.Pi * radius * radius, <span class="literal">nil</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    radius := <span class="number">-20.0</span></span><br><span class="line">    area, err := circleArea(radius)</span><br><span class="line">    <span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">        fmt.Println(err)</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    &#125;</span><br><span class="line">    fmt.Printf(<span class="string">"Area of circle %0.2f"</span>, area)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面的程序中，我们检查半径是否小于零（第 10 行）。如果半径小于零，我们会返回等于 0 的面积，以及相应的错误信息。如果半径大于零，则会计算出面积，并返回值为 <code>nil</code> 的错误（第 13 行）。</p>
<p>在 <code>main</code> 函数里，我们在第 19 行检查错误是否等于 <code>nil</code>。如果不是 <code>nil</code>，我们会打印出错误并返回，否则我们会打印出圆的面积。</p>
<p>在我们的程序中，半径小于零，因此打印出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Area calculation failed, radius is less than zero</span><br></pre></td></tr></table></figure>

<h2 id="使用-Errorf-给错误添加更多信息"><a href="#使用-Errorf-给错误添加更多信息" class="headerlink" title="使用 Errorf 给错误添加更多信息"></a>使用 Errorf 给错误添加更多信息</h2><p>上面的程序效果不错，但是如果我们能够打印出当前圆的半径，那就更好了。这就要用到 [<code>fmt</code>]包中的 [<code>Errorf</code>] 函数了。<code>Errorf</code> 函数会根据格式说明符，规定错误的格式，并返回一个符合该错误的[字符串]。</p>
<p>接下来我们使用 <code>Errorf</code> 函数来改进我们的程序。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (  </span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">    <span class="string">"math"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">circleArea</span><span class="params">(radius <span class="keyword">float64</span>)</span> <span class="params">(<span class="keyword">float64</span>, error)</span></span> &#123;  </span><br><span class="line">    <span class="keyword">if</span> radius &lt; <span class="number">0</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>, fmt.Errorf(<span class="string">"Area calculation failed, radius %0.2f is less than zero"</span>, radius)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> math.Pi * radius * radius, <span class="literal">nil</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    radius := <span class="number">-20.0</span></span><br><span class="line">    area, err := circleArea(radius)</span><br><span class="line">    <span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">        fmt.Println(err)</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    &#125;</span><br><span class="line">    fmt.Printf(<span class="string">"Area of circle %0.2f"</span>, area)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面的程序中，我们使用 <code>Errorf</code>（第 10 行）打印了发生错误的半径。程序运行后会输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Area calculation failed, radius -20.00 is less than zero</span><br></pre></td></tr></table></figure>

<h2 id="使用结构体类型和字段提供错误的更多信息"><a href="#使用结构体类型和字段提供错误的更多信息" class="headerlink" title="使用结构体类型和字段提供错误的更多信息"></a>使用结构体类型和字段提供错误的更多信息</h2><p>错误还可以用实现了 <code>error</code> [接口]的结构体来表示。这种方式可以更加灵活地处理错误。在上面例子中，如果我们希望访问引发错误的半径，现在唯一的方法就是解析错误的描述信息 <code>Area calculation failed, radius -20.00 is less than zero</code>。这样做不太好，因为一旦描述信息发生变化，程序就会出错。</p>
<p>我们会使用标准库里采用的方法，在上一教程中“断言底层结构体类型，使用结构体字段获取更多信息”这一节，我们讲解了这一方法，可以使用结构体字段来访问引发错误的半径。我们会创建一个实现 <code>error</code> 接口的结构体类型，并使用它的字段来提供关于错误的更多信息。</p>
<p>第一步就是创建一个表示错误的结构体类型。错误类型的命名约定是名称以 <code>Error</code> 结尾。因此我们不妨把结构体类型命名为 <code>areaError</code>。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> areaError <span class="keyword">struct</span> &#123;  </span><br><span class="line">    err    <span class="keyword">string</span></span><br><span class="line">    radius <span class="keyword">float64</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面的结构体类型有一个 <code>radius</code> 字段，它存储了与错误有关的半径，而 <code>err</code> 字段存储了实际的错误信息。</p>
<p>下一步是实现 <code>error</code> 接口。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(e *areaError)</span> <span class="title">Error</span><span class="params">()</span> <span class="title">string</span></span> &#123;  </span><br><span class="line">    <span class="keyword">return</span> fmt.Sprintf(<span class="string">"radius %0.2f: %s"</span>, e.radius, e.err)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面的代码中，我们使用指针接收者 <code>*areaError</code>，实现了 <code>error</code> 接口的 <code>Error() string</code> 方法。该方法打印出半径和关于错误的描述。</p>
<p>现在我们来编写 <code>main</code> 函数和 <code>circleArea</code> 函数来完成整个程序。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (  </span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">    <span class="string">"math"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> areaError <span class="keyword">struct</span> &#123;  </span><br><span class="line">    err    <span class="keyword">string</span></span><br><span class="line">    radius <span class="keyword">float64</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(e *areaError)</span> <span class="title">Error</span><span class="params">()</span> <span class="title">string</span></span> &#123;  </span><br><span class="line">    <span class="keyword">return</span> fmt.Sprintf(<span class="string">"radius %0.2f: %s"</span>, e.radius, e.err)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">circleArea</span><span class="params">(radius <span class="keyword">float64</span>)</span> <span class="params">(<span class="keyword">float64</span>, error)</span></span> &#123;  </span><br><span class="line">    <span class="keyword">if</span> radius &lt; <span class="number">0</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>, &amp;areaError&#123;<span class="string">"radius is negative"</span>, radius&#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> math.Pi * radius * radius, <span class="literal">nil</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    radius := <span class="number">-20.0</span></span><br><span class="line">    area, err := circleArea(radius)</span><br><span class="line">    <span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> err, ok := err.(*areaError); ok &#123;</span><br><span class="line">            fmt.Printf(<span class="string">"Radius %0.2f is less than zero"</span>, err.radius)</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        &#125;</span><br><span class="line">        fmt.Println(err)</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    &#125;</span><br><span class="line">    fmt.Printf(<span class="string">"Area of rectangle1 %0.2f"</span>, area)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><a href="https://play.golang.org/p/OTs7J0adQg" target="_blank" rel="noopener">在 playground 上运行</a></p>
<p>在上面的程序中，<code>circleArea</code>（第 17 行）用于计算圆的面积。该函数首先检查半径是否小于零，如果小于零，它会通过错误半径和对应错误信息，创建一个 <code>areaError</code> 类型的值，然后返回 <code>areaError</code> 值的地址，与此同时 <code>area</code> 等于 0（第 19 行）。<strong>于是我们提供了更多的错误信息（即导致错误的半径），我们使用了自定义错误的结构体字段来定义它</strong>。</p>
<p>如果半径是非负数，该函数会在第 21 行计算并返回面积，同时错误值为 <code>nil</code>。</p>
<p>在 <code>main</code> 函数的 26 行，我们试图计算半径为 -20 的圆的面积。由于半径小于零，因此会导致一个错误。</p>
<p>我们在第 27 行检查了错误是否为 <code>nil</code>，并在下一行断言了 <code>*areaError</code> 类型。<strong>如果错误是 *areaError 类型，我们就可以用 err.radius 来获取错误的半径（第 29 行），打印出自定义错误的消息，最后程序返回退出</strong>。</p>
<p>如果断言错误，我们就在第 32 行打印该错误，并返回。如果没有发生错误，在第 35 行会打印出面积。</p>
<p>该程序会输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Radius -20.00 is less than zero</span><br></pre></td></tr></table></figure>

<p>下面我们来使用上一教程提到的[第二种方法]，使用自定义错误类型的方法来提供错误的更多信息。</p>
<h2 id="使用结构体类型的方法来提供错误的更多信息"><a href="#使用结构体类型的方法来提供错误的更多信息" class="headerlink" title="使用结构体类型的方法来提供错误的更多信息"></a>使用结构体类型的方法来提供错误的更多信息</h2><p>在本节里，我们会编写一个计算矩形面积的程序。如果长或宽小于零，程序就会打印出错误。</p>
<p>第一步就是创建一个表示错误的结构体。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> areaError <span class="keyword">struct</span> &#123;  </span><br><span class="line">    err    <span class="keyword">string</span> <span class="comment">//error description</span></span><br><span class="line">    length <span class="keyword">float64</span> <span class="comment">//length which caused the error</span></span><br><span class="line">    width  <span class="keyword">float64</span> <span class="comment">//width which caused the error</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面的结构体类型除了有一个错误描述字段，还有可能引发错误的宽和高。</p>
<p>现在我们有了错误类型，我们来实现 <code>error</code> 接口，并给该错误类型添加两个方法，使它提供了更多的错误信息。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(e *areaError)</span> <span class="title">Error</span><span class="params">()</span> <span class="title">string</span></span> &#123;  </span><br><span class="line">    <span class="keyword">return</span> e.err</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(e *areaError)</span> <span class="title">lengthNegative</span><span class="params">()</span> <span class="title">bool</span></span> &#123;  </span><br><span class="line">    <span class="keyword">return</span> e.length &lt; <span class="number">0</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(e *areaError)</span> <span class="title">widthNegative</span><span class="params">()</span> <span class="title">bool</span></span> &#123;  </span><br><span class="line">    <span class="keyword">return</span> e.width &lt; <span class="number">0</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面的代码片段中，我们从 <code>Error() string</code> 方法中返回了关于错误的描述。当 <code>length</code> 小于零时，<code>lengthNegative() bool</code> 方法返回 <code>true</code>，而当 <code>width</code> 小于零时，<code>widthNegative() bool</code> 方法返回 <code>true</code>。<strong>这两个方法都提供了关于错误的更多信息，在这里，它提示我们计算面积失败的原因（长度为负数或者宽度为负数）。于是我们就有了两个错误类型结构体的方法，来提供更多的错误信息</strong>。</p>
<p>下一步就是编写计算面积的函数。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">rectArea</span><span class="params">(length, width <span class="keyword">float64</span>)</span> <span class="params">(<span class="keyword">float64</span>, error)</span></span> &#123;  </span><br><span class="line">    err := <span class="string">""</span></span><br><span class="line">    <span class="keyword">if</span> length &lt; <span class="number">0</span> &#123;</span><br><span class="line">        err += <span class="string">"length is less than zero"</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> width &lt; <span class="number">0</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> err == <span class="string">""</span> &#123;</span><br><span class="line">            err = <span class="string">"width is less than zero"</span></span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            err += <span class="string">", width is less than zero"</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> err != <span class="string">""</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>, &amp;areaError&#123;err, length, width&#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> length * width, <span class="literal">nil</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面的 <code>rectArea</code> 函数检查了长或宽是否小于零，如果小于零，<code>rectArea</code> 会返回一个错误信息，否则 <code>rectArea</code> 会返回矩形的面积和一个值为 <code>nil</code> 的错误。</p>
<p>让我们创建 <code>main</code> 函数来完成整个程序。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    length, width := <span class="number">-5.0</span>, <span class="number">-9.0</span></span><br><span class="line">    area, err := rectArea(length, width)</span><br><span class="line">    <span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> err, ok := err.(*areaError); ok &#123;</span><br><span class="line">            <span class="keyword">if</span> err.lengthNegative() &#123;</span><br><span class="line">                fmt.Printf(<span class="string">"error: length %0.2f is less than zero\n"</span>, err.length)</span><br><span class="line"></span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> err.widthNegative() &#123;</span><br><span class="line">                fmt.Printf(<span class="string">"error: width %0.2f is less than zero\n"</span>, err.width)</span><br><span class="line"></span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        &#125;</span><br><span class="line">        fmt.Println(err)</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    &#125;</span><br><span class="line">    fmt.Println(<span class="string">"area of rect"</span>, area)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在 <code>main</code> 程序中，我们检查了错误是否为 <code>nil</code>（第 4 行）。如果错误值不是 <code>nil</code>，我们会在下一行断言 <code>*areaError</code> 类型。然后，我们使用 <code>lengthNegative()</code> 和 <code>widthNegative()</code> 方法，检查错误的原因是长度小于零还是宽度小于零。这样我们就使用了错误结构体类型的方法，来提供更多的错误信息。</p>
<p>如果没有错误发生，就会打印矩形的面积。</p>
<p>下面是整个程序的代码供你参考。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> areaError <span class="keyword">struct</span> &#123;  </span><br><span class="line">    err    <span class="keyword">string</span>  <span class="comment">//error description</span></span><br><span class="line">    length <span class="keyword">float64</span> <span class="comment">//length which caused the error</span></span><br><span class="line">    width  <span class="keyword">float64</span> <span class="comment">//width which caused the error</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(e *areaError)</span> <span class="title">Error</span><span class="params">()</span> <span class="title">string</span></span> &#123;  </span><br><span class="line">    <span class="keyword">return</span> e.err</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(e *areaError)</span> <span class="title">lengthNegative</span><span class="params">()</span> <span class="title">bool</span></span> &#123;  </span><br><span class="line">    <span class="keyword">return</span> e.length &lt; <span class="number">0</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(e *areaError)</span> <span class="title">widthNegative</span><span class="params">()</span> <span class="title">bool</span></span> &#123;  </span><br><span class="line">    <span class="keyword">return</span> e.width &lt; <span class="number">0</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">rectArea</span><span class="params">(length, width <span class="keyword">float64</span>)</span> <span class="params">(<span class="keyword">float64</span>, error)</span></span> &#123;  </span><br><span class="line">    err := <span class="string">""</span></span><br><span class="line">    <span class="keyword">if</span> length &lt; <span class="number">0</span> &#123;</span><br><span class="line">        err += <span class="string">"length is less than zero"</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> width &lt; <span class="number">0</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> err == <span class="string">""</span> &#123;</span><br><span class="line">            err = <span class="string">"width is less than zero"</span></span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            err += <span class="string">", width is less than zero"</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> err != <span class="string">""</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>, &amp;areaError&#123;err, length, width&#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> length * width, <span class="literal">nil</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    length, width := <span class="number">-5.0</span>, <span class="number">-9.0</span></span><br><span class="line">    area, err := rectArea(length, width)</span><br><span class="line">    <span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> err, ok := err.(*areaError); ok &#123;</span><br><span class="line">            <span class="keyword">if</span> err.lengthNegative() &#123;</span><br><span class="line">                fmt.Printf(<span class="string">"error: length %0.2f is less than zero\n"</span>, err.length)</span><br><span class="line"></span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> err.widthNegative() &#123;</span><br><span class="line">                fmt.Printf(<span class="string">"error: width %0.2f is less than zero\n"</span>, err.width)</span><br><span class="line"></span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        &#125;</span><br><span class="line">        fmt.Println(err)</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    &#125;</span><br><span class="line">    fmt.Println(<span class="string">"area of rect"</span>, area)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>该程序会打印输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">error: length -5.00 is less than zero  </span><br><span class="line">error: width -9.00 is less than zero</span><br></pre></td></tr></table></figure>

<p>在上一教程[错误处理]中，我们介绍了三种提供更多错误信息的方法，现在我们已经看了其中两个示例。</p>
<p>第三种方法使用的是直接比较，比较简单。我留给读者作为练习，你们可以试着使用这种方法来给出自定义错误的更多信息。</p>
<p>本教程到此结束。</p>
<p>简单概括一下本教程讨论的内容：</p>
<ul>
<li>使用 <code>New</code> 函数创建自定义错误</li>
<li>使用 <code>Error</code> 添加更多错误信息</li>
<li>使用结构体类型和字段，提供更多错误信息</li>
<li>使用结构体类型和方法，提供更多错误信息</li>
</ul>
</section>
    <!-- Tags START -->
    
      <div class="tags">
        <span>Tags:</span>
        
  <a href="/tags#Go" >
    <span class="tag-code">Go</span>
  </a>

      </div>
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/go/4-Go%E8%AF%AD%E8%A8%80%E6%A1%86%E6%9E%B6/04-Go%E8%AF%AD%E8%A8%80%E4%B9%8B%E5%BE%AE%E6%9C%8D%E5%8A%A1/">
        <span class="nav-arrow">← </span>
        
          Go语言之微服务
        
      </a>
    
    
      <a class="nav-right" href="/go/3-Go%E8%AF%AD%E8%A8%80%E5%B8%B8%E7%94%A8%E6%A0%87%E5%87%86%E5%BA%93/04-Go%E8%AF%AD%E8%A8%80%E4%B9%8Blog/">
        
          Go语言之log
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
      <div class="money-like">
        <div class="reward-btn">
          赏
          <span class="money-code">
            <span class="alipay-code">
              <div class="code-image"></div>
              <b>使用支付宝打赏</b>
            </span>
            <span class="wechat-code">
              <div class="code-image"></div>
              <b>使用微信打赏</b>
            </span>
          </span>
        </div>
        <p class="notice">点击上方按钮,请我喝杯咖啡！</p>
      </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
      <div class="qrcode">
        <canvas id="share-qrcode"></canvas>
        <p class="notice">扫描二维码，分享此文章</p>
      </div>
    
    <!-- 二维码 END -->
    
      <!-- Gitment START -->
      <div id="comments"></div>
      <!-- Gitment END -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
  <!-- 不蒜子统计 -->
    <strong class="toc-title">目录</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#使用-New-函数创建自定义错误"><span class="toc-nav-text">使用 New 函数创建自定义错误</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#使用-Errorf-给错误添加更多信息"><span class="toc-nav-text">使用 Errorf 给错误添加更多信息</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#使用结构体类型和字段提供错误的更多信息"><span class="toc-nav-text">使用结构体类型和字段提供错误的更多信息</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#使用结构体类型的方法来提供错误的更多信息"><span class="toc-nav-text">使用结构体类型的方法来提供错误的更多信息</span></a></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'http://www.liuqingzheng.top/go/2-Go语言基础/31-自定义错误/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


  <script>
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });
  </script>



  <script>
    var gitmentConfig = "liuqingzheng";
    if (gitmentConfig !== 'undefined') {
      var gitment = new Gitment({
        id: "31-自定义错误",
        owner: "liuqingzheng",
        repo: "FuckBlog",
        oauth: {
          client_id: "32a4076431cf39d0ecea",
          client_secret: "94484bd79b3346a949acb2fda3c8a76ce16990c6"
        },
        theme: {
          render(state, instance) {
            const container = document.createElement('div')
            container.lang = "en-US"
            container.className = 'gitment-container gitment-root-container'
            container.appendChild(instance.renderHeader(state, instance))
            container.appendChild(instance.renderEditor(state, instance))
            container.appendChild(instance.renderComments(state, instance))
            container.appendChild(instance.renderFooter(state, instance))
            return container;
          }
        }
      })
      gitment.render(document.getElementById('comments'))
    }
  </script>




    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
<!-- 不蒜子统计 -->
<span id="busuanzi_container_site_pv">
     本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<span class="post-meta-divider">|</span>
<span id="busuanzi_container_site_uv" style='display:none'>
     本站访客数<span id="busuanzi_value_site_uv"></span>人
</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



  <p class="copyright">
    &copy; 2021 | Proudly powered by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank">小猿取经</a>
    <br>
    Theme by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank" rel="noopener">小猿取经</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("//cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>





<!-- Baidu Tongji -->

<script>
    var _baId = 'c5fd96eee1193585be191f318c3fa725';
    // Originial
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?" + _baId;
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
</script>


<script src="/js/script.js"></script>


<script src="/js/search.js"></script>


<script src="/js/load.js"></script>



  <span class="local-search local-search-google local-search-plugin" style="right: 50px;top: 70px;;position:absolute;z-index:2;">
      <input type="search" placeholder="站内搜索" id="local-search-input" class="local-search-input-cls" style="">
      <div id="local-search-result" class="local-search-result-cls"></div>
  </span>


  </body>
</html>